package com.fqgj.sentry.biz.mc;

import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.sentry.biz.mc.domain.RedisOperate;
import com.fqgj.sentry.common.cache.RedisUserInfo;
import com.fqgj.sentry.common.exception.BizException;
import com.fqgj.sentry.common.exception.enums.ErrorCodeEnums;
import com.fqgj.sentry.common.utils.HashUtils;
import com.fqgj.sentry.manage.entity.McUserEntity;
import com.fqgj.sentry.manage.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * Created by ykpbean kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2017-07-15 下午8:20
 */

@Component
public class LoginBusiness {

    @Autowired
    private RedisClient redisClient;
    @Autowired
    private UserService userService;

    public String Login(String account, String password) {

        McUserEntity mcUserEntity = userService.selectByAccount(account);
        String pwd = mcUserEntity.getPassword();
        if (!pwd.equals(HashUtils.md5(password))) {
            throw new BizException(ErrorCodeEnums.password_error);
        }
        RedisUserInfo redisUserInfo = new RedisUserInfo()
                .setUserId(mcUserEntity.getId())
                .setMerchantId(mcUserEntity.getMerchantId());
        String token = UUID.randomUUID().toString();
        RedisOperate.delRedisUserCache(redisClient, mcUserEntity.getId());
        RedisOperate.setRedisUserCache(redisClient, mcUserEntity.getId(), token, redisUserInfo);
        return token;
    }

    public void LoginOut(Long userId) {
        RedisOperate.delRedisUserCache(redisClient, userId);
    }
}
